const bcrypt = require('bcryptjs')
const db = require('../config/database')
const { success, error } = require('../utils/responseHelper')

const userController = {
  // 获取用户列表（管理员）
  async getUsers(req, res, next) {
    try {
      const { role, page = 1, limit = 10, search } = req.query
      const offset = (page - 1) * limit

      let query =
        'SELECT id, username, name, email, role, created_at, updated_at FROM users'
      const conditions = []
      const params = []
      const countParams = []

      if (role) {
        conditions.push('role = ?')
        params.push(role)
        countParams.push(role)
      }
      if (search) {
        conditions.push('(username LIKE ? OR name LIKE ? OR email LIKE ?)')
        const searchTerm = `%${search}%`
        params.push(searchTerm, searchTerm, searchTerm)
        countParams.push(searchTerm, searchTerm, searchTerm)
      }

      if (conditions.length > 0) {
        query += ' WHERE ' + conditions.join(' AND ')
      }
      query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'
      params.push(parseInt(limit), offset)

      const [users] = await db.execute(query, params)

      // 获取总数
      let countQuery = 'SELECT COUNT(*) as total FROM users'
      if (conditions.length > 0) {
        countQuery += ' WHERE ' + conditions.join(' AND ')
      }

      const [countResult] = await db.execute(countQuery, countParams)
      success(res, {
        users,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: countResult[0].total,
          pages: Math.ceil(countResult[0].total / limit),
        },
      })
    } catch (err) {
      next(err)
    }
  },

  // 创建用户（管理员）
  async createUser(req, res, next) {
    try {
      const { username, password, name, email, role = 'student' } = req.body

      // 检查用户名是否已存在
      const [existingUsers] = await db.execute(
        'SELECT id FROM users WHERE username = ?',
        [username]
      )
      if (existingUsers.length > 0) {
        return error(res, '用户名已存在', 400)
      }

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 12)

      // 创建用户
      const [result] = await db.execute(
        'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)',
        [username, hashedPassword, name, email, role]
      )
      success(
        res,
        {
          id: result.insertId,
          username,
          name,
          email,
          role,
        },
        '用户创建成功'
      )
    } catch (err) {
      next(err)
    }
  },

  // 获取单个用户信息 (管理员或用户自己)
  async getUserById(req, res, next) {
    try {
      const { id } = req.params // User ID from URL
      const requesterId = req.user.id
      const requesterRole = req.user.role

      if (requesterRole !== 'admin' && parseInt(id) !== requesterId) {
        return error(res, '权限不足', 403)
      }

      const [users] = await db.execute(
        'SELECT id, username, name, email, role, created_at, updated_at FROM users WHERE id = ?',
        [id]
      )

      if (users.length === 0) {
        return error(res, '用户不存在', 404)
      }
      success(res, users[0])
    } catch (err) {
      next(err)
    }
  },

  // 更新用户信息
  async updateUser(req, res, next) {
    try {
      const { id } = req.params // 用户ID
      const { name, email, role, password } = req.body
      const requesterId = req.user.id
      const requesterRole = req.user.role

      // 权限检查: 管理员可以更新任何人，普通用户只能更新自己
      if (requesterRole !== 'admin' && parseInt(id) !== requesterId) {
        return error(res, '权限不足，无法更新此用户信息', 403)
      }

      // 检查用户是否存在
      const [users] = await db.execute('SELECT * FROM users WHERE id = ?', [id])
      if (users.length === 0) {
        return error(res, '用户不存在', 404)
      }

      const updateFields = []
      const updateValues = []

      if (name !== undefined) {
        updateFields.push('name = ?')
        updateValues.push(name)
      }
      if (email !== undefined) {
        // 可以在这里添加邮箱格式验证或唯一性检查（如果需要）
        updateFields.push('email = ?')
        updateValues.push(email)
      }
      // 只有管理员可以修改角色
      if (role !== undefined && requesterRole === 'admin') {
        updateFields.push('role = ?')
        updateValues.push(role)
      } else if (
        role !== undefined &&
        requesterRole !== 'admin' &&
        users[0].role !== role
      ) {
        // 非管理员尝试修改角色 - 忽略或报错
        console.warn(
          `User ${requesterId} attempted to change role of user ${id} without admin privileges.`
        )
        // return error(res, '无权修改用户角色', 403); // 或者静默忽略
      }

      if (password !== undefined && password !== '') {
        // 允许更新密码
        const hashedPassword = await bcrypt.hash(password, 12)
        updateFields.push('password = ?')
        updateValues.push(hashedPassword)
      }

      if (updateFields.length === 0) {
        return error(res, '没有要更新的字段', 400)
      }

      updateFields.push('updated_at = NOW()')
      updateValues.push(id)

      await db.execute(
        `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`,
        updateValues
      )
      success(res, null, '用户信息更新成功')
    } catch (err) {
      next(err)
    }
  },

  // 删除用户（管理员）
  async deleteUser(req, res, next) {
    try {
      const { id } = req.params

      // 防止管理员删除自己 (可选逻辑)
      if (parseInt(id) === req.user.id) {
        return error(res, '无法删除当前登录的管理员账户', 400)
      }

      // 检查是否有相关的考试记录
      const [records] = await db.execute(
        'SELECT COUNT(*) as count FROM exam_records WHERE user_id = ?',
        [id]
      )
      if (records[0].count > 0) {
        // 可以选择软删除或提示先处理相关数据
        return error(
          res,
          '该用户有考试记录，无法直接删除。请先处理相关考试数据或考虑禁用用户。',
          400
        )
      }

      // 检查用户是否创建了考试 (如果 created_by 是外键)
      const [createdExams] = await db.execute(
        'SELECT COUNT(*) as count FROM exams WHERE created_by = ?',
        [id]
      )
      if (createdExams[0].count > 0) {
        return error(
          res,
          '该用户创建了考试，无法直接删除。请先处理相关考试或将其分配给其他管理员。',
          400
        )
      }

      const [result] = await db.execute('DELETE FROM users WHERE id = ?', [id])
      if (result.affectedRows === 0) {
        return error(res, '用户不存在', 404)
      }
      success(res, null, '用户删除成功')
    } catch (err) {
      next(err)
    }
  },

  // 获取用户统计信息
  async getUserStats(req, res, next) {
    try {
      const [stats] = await db.execute(`
        SELECT 
          COUNT(*) as total_users,
          COUNT(CASE WHEN role = 'student' THEN 1 END) as student_count,
          COUNT(CASE WHEN role = 'admin' THEN 1 END) as admin_count,
          COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as new_users_30_days
        FROM users
      `)
      success(res, stats[0])
    } catch (err) {
      next(err)
    }
  },
}

module.exports = userController
